//
//  GameOverScene.swift
//  aircraftBattle1
//
//  Created by 许洋 on 2024/5/16.
//

import SpriteKit
import GameKit

class GameOverScene:BaseScene {
    private var bgNode :SKSpriteNode!
    private var playNode :SKSpriteNode!
    private var goHomeNode :SKSpriteNode!

    private var cScoreNode:SKLabelNode! // 当局分数
    private var hScoreNode:SKLabelNode!    // 最高分数
    private var selectIndex:Int = 0
    private var airTypes:Array<String> = []
    private var mapTypes:Array<String> = []
    private var mapSelectIndex:Int = 0

    override func didMove(to view: SKView) {
        // 找到 名称为Play的节点
        bgNode = childNode(withName: "bg") as? SKSpriteNode
        playNode = childNode(withName: "Play") as? SKSpriteNode
        goHomeNode = childNode(withName: "GoHome") as? SKSpriteNode
        cScoreNode = childNode(withName: "score") as? SKLabelNode
        hScoreNode    = childNode(withName: "highScore") as? SKLabelNode
        cScoreNode.text = "\(UserDefaults.standard.integer(forKey: "CURRENTSCORE"))"   // 取出当前分数
        hScoreNode.text    = "\(UserDefaults.standard.integer(forKey: "HIGHSCORE"))" // 取出沙盒中的最高分数
        
        airTypes = ["air_y","air_b","air_g"]
        mapTypes = ["bg_0","bg_1","bg_2"]
        selectIndex =  UserDefaults.standard.integer(forKey: "AIRTYPE")
        mapSelectIndex =  UserDefaults.standard.integer(forKey: "MAPTYPE")
        bgNode.texture = SKTexture(imageNamed: mapTypes[mapSelectIndex])
        bgNode.size = self.size
        enumerateChildNodes(withName: "bgNode") { (node, _) in
            guard let sprite = node as? SKSpriteNode else {
                return
            }
            sprite.texture = SKTexture(imageNamed: self.mapTypes[self.mapSelectIndex])
            sprite.size = self.size
        }

    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
        }
        let touchLocation = touch.location(in: self)
        // 获得点击位置在Play节点Node
        if playNode.contains(touchLocation) {
            let reveal = SKTransition.doorsOpenVertical(withDuration: TimeInterval(0.5))
            let scene = BattleScene(fileNamed: "BattleScene")
            scene?.viewController = self.viewController
            scene?.size = self.size
            scene?.scaleMode = .aspectFill
            self.view?.presentScene(scene!, transition: reveal)
        }
        if goHomeNode.contains(touchLocation) {
            let reveal = SKTransition.doorsCloseHorizontal(withDuration: TimeInterval(0.5))
            let scene = HomeScene(fileNamed: "HomeScene")
            scene?.viewController = self.viewController
            scene?.size = self.size
            scene?.scaleMode = .aspectFill
            self.view?.presentScene(scene!, transition: reveal)
        }

    }
    
}
